package ArticleService

import (
	"context"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/request/ArticleReq"
	"gdshop-back-end-go/common/response"
	"github.com/PuerkitoBio/goquery"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/util/gconv"
	"strings"
)

func Content(ctx context.Context, parames *ArticleReq.Content) *response.JsonResponse {
	if parames.Id < 1 && parames.Type == "" {
		return response.FailByRequestMessage(nil, "参数不能为空")
	}
	where := g.Map{}

	if parames.Id > 0 {
		where["a.id"] = parames.Id
	} else {
		where["a.alias"] = parames.Type
	}

	one, err := toolsDb.GetUnSafaTableAddDeleteWhere(ctx, "article").As("a").
		Fields("a.title,ac.content").
		LeftJoin("article_content ac", "ac.article_id = a.id").Where(where).One()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}

	if one.IsEmpty() {
		return response.FailByRequestMessage(nil, "未找到数据")
	}
	oneMap := one.Map()
	// 处理 content 里面的图片,替换地址
	photoBaseUrl := g.Cfg().GetString("site.PhotoUrlProfix")
	content, err := replaceContentImgSrc(gconv.String(oneMap["content"]), photoBaseUrl)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	oneMap["content"] = content

	return response.SuccessByRequestMessageData(nil, "成功", oneMap)
}

// 为 content 里面的 img src 增加前缀
// contont 内容
// profix 图片前缀
func replaceContentImgSrc(contont, profix string) (string, error) {
	doc, err := goquery.NewDocumentFromReader(strings.NewReader(contont))
	if err != nil {
		return "", err
	}
	doc.Find("img").Each(func(i int, selection *goquery.Selection) {
		imgSrc, ok := selection.Attr("src")
		if ok {
			selection.SetAttr("src", profix+imgSrc)
		}
	})
	html, err := doc.Html()
	if err != nil {
		return "", err
	}
	return html, nil
}
